import { PlusOutlined, ExportOutlined } from '@ant-design/icons';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { downloadExcel } from '@/utils/excelUtils';
import { getTodayTotalData } from '@/services/dashBoardService';
import EditorPage from './components/editor';
import { cloumsGet } from '@/services/colums';
import { newIndicatorValue } from '@/utils';

const CloumsList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [tableData, setTableData] = useState<any[]>([]);
  const [indicators, setIndicators] = useState<CLOUMS.CLOUMSListItem[]>([]);

  const [columsArr, setColumsArr] = useState<any>([]);
  // 弹出窗 控制表格头部增减
  const [editorModalVisible, setEditorModalVisible] = useState<boolean>(false);

  // 选中表头
  const [indicatSelectTab, setIndicatSelectTab] = useState<any[]>([]);

  /* 表格 排序方法 */
  const sortFn = (a: any, b: any, dataIndex: string) => a[dataIndex] - b[dataIndex];

  const columns: ProColumns<any>[] = [
    {
      title: '日期',
      dataIndex: 'date',
      render: (_dom, data) => {
        return data.date.replace('.', '-');
      },
    },
    {
      title: '新增境外输入病例',
      dataIndex: 'cn_addjwsrNum',
      sorter: (a, b) => sortFn(a, b, 'cn_addjwsrNum'),
    },
    {
      title: '现存无症状病例',
      dataIndex: 'cn_asymptomNum',
      sorter: (a, b) => sortFn(a, b, 'cn_asymptomNum'),
    },
    {
      title: '新增确诊病例',
      dataIndex: 'cn_conadd',
      sorter: (a, b) => sortFn(a, b, 'cn_conadd'),
    },
    {
      title: '治愈人数',
      dataIndex: 'cn_cureNum',
      sorter: (a, b) => sortFn(a, b, 'cn_cureNum'),
    },
    {
      title: '治愈比例',
      dataIndex: 'cn_cureRate',
      sorter: (a, b) => sortFn(a, b, 'cn_cureRate'),
    },
    {
      title: '死亡人数',
      dataIndex: 'cn_deathNum',
      sorter: (a, b) => sortFn(a, b, 'cn_asymptomNum'),
    },
    {
      title: '死亡比例',
      dataIndex: 'cn_deathRate',
      sorter: (a, b) => sortFn(a, b, 'cn_asymptomNum'),
    },
    {
      title: '现存确诊人',
      dataIndex: 'cn_econNum',
      sorter: (a, b) => sortFn(a, b, 'cn_asymptomNum'),
    },
    {
      title: '现存重症',
      dataIndex: 'cn_heconNum',
      sorter: (a, b) => sortFn(a, b, 'cn_heconNum'),
    },
    ...columsArr,
  ];

  /* Excel 导出方法 */
  function onExportExcel() {
    downloadExcel({
      filename: '历史疫情数据',
      sheets: [
        {
          sheetName: 'test',
          columns: columns,
          dataSource: tableData,
        },
      ],
    });
  }
  /* 获取疫情数据 */
  const getDiseaseDatas = () => {
    getTodayTotalData({}).then((res) => {
      setTableData(res.data.historylist);
    });
  };

  /* 获取指标数据 */
  const getIndicatorsDatas = () => {
    cloumsGet({ type: '3' }).then((res) => {
      setIndicators(res.data);
    });
  };

  useEffect(() => {
    getDiseaseDatas();
    getIndicatorsDatas();
  }, []);

  // 渲染表头
  const setTableFn = (checkedValues: any[]) => {
    console.log(checkedValues);
    const addTabArr: CLOUMS.CLOUMSListItem[] = indicators.filter((ell) =>
      checkedValues.includes(ell.code),
    );

    setColumsArr(
      addTabArr.map((el) => ({
        title: el.name,
        dataIndex: el.code,
      })),
    );

    const newData = tableData.map((el) => {
      return {
        ...el,
        ...addTabArr.reduce((result: any, current: any) => {
          return {
            ...result,
            [current.code]: newIndicatorValue(current, el),
          };
        }, {}),
      };
    });
    setTableData(newData);
    // newIndicatorValue();
    // setTableData()
    return true;
  };

  return (
    <PageContainer>
      <ProTable<CLOUMS.CLOUMSListItem, CLOUMS.CLOUMSParams>
        actionRef={actionRef}
        rowKey="date"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditorModalVisible(true);
            }}
          >
            <PlusOutlined />
            新增表头
          </Button>,
          <Button type="primary" key="export" onClick={() => onExportExcel()}>
            <ExportOutlined />
            导出
          </Button>,
        ]}
        dataSource={tableData}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />
      {editorModalVisible ? (
        <EditorPage
          tabArr={indicators}
          selectTab={indicatSelectTab}
          setSelectTab={setIndicatSelectTab}
          renderTable={setTableFn}
          pageShow={editorModalVisible}
          pageShowFn={setEditorModalVisible}
        />
      ) : (
        ''
      )}
    </PageContainer>
  );
};

export default CloumsList;
